package com.stockz.ui.swing.charting.display.indicator;

import java.awt.Graphics2D;

import org.springframework.stereotype.Component;

import com.stockz.core.util.ListUtil;
import com.stockz.ui.swing.charting.painter.indicator.LineIndicatorPainter;
import com.stockz.ui.swing.charting.util.UIChartingConstant.OVERLAY;

@Component
public class RelativeStrengthIndex extends
		AbstractDisplayableIndicatorConfiguration {

	public static class Configuration{
		private int span = 20;

		public int getSpan() {
			return span;
		}

		public void setSpan(int span) {
			this.span = span;
		}
	}
	
	public static double value(double[] barValues, int span){
		return 0;
	}
	
	public static double[] values(double[] barValues, int span){
		if(barValues != null && span > 0 && barValues.length > span){
			double[] values = new double[barValues.length];
			double[] gain = new double[barValues.length];
			double[] loss = new double[barValues.length];
			
			for(int i = barValues.length-2; i >=0; i--){
				double change = barValues[i] - barValues[i+1]; 
				if(i >=  barValues.length - span){
					if(change > 0){
						gain[i] += change;
					}else{
						loss[i] += change;
					}
					gain[i] = gain[i]/span;
					loss[i] = loss[i]/span;
				}else{
					if(change > 0){
						gain[i] = (gain[i+1]*(span - 1) + change)/span;
					}else{
						loss[i] = (loss[i+1]*(span - 1) + change)/span;
					}
				}
				if(loss[i] == 0){
					loss[i] = 0.001;
				}
				values[i] = 100 - 100/(1 + (gain[i]/loss[i]));
			}
			return values;
		}
		return new double[0];
	}
	
	private Configuration configuration = new Configuration();
	
	@Override
	public String getFullName() {
		return "Relative Strength Index";
	}

	@Override
	public String getShortName() {
		return "RSI";
	}

	@Override
	public String getDescription() {
		return getShortName()+", "+configuration.getSpan();
	}

	@Override
	public OVERLAY getOverlay() {
		return OVERLAY.INDEPENDENT;
	}

	@Override
	public boolean isOverlappable() {
		return true;
	}

	@Override
	public void paint(Graphics2D g) {
		LineIndicatorPainter.paint(g, this);
	}

	@Override
	public Object getConfiguration() {
		return configuration;
	}

	@Override
	public void refreshValues() {
		setValues(values(ListUtil.convert(getStockChartPanel().getStockChartPanelState().getBarList(),getBarValueType()),configuration.getSpan()));
	}

}
